package org.i9.slb.platform.anseko.provider.repository;

import org.i9.slb.platform.anseko.provider.dto.CommandExecuteDto;
import org.i9.slb.platform.anseko.provider.repository.mapper.CommandExecuteRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.UUID;

/**
 * 命令执行dao
 *
 * @author R12
 * @date 2018年9月4日 10:50:31
 */
@Repository
public class CommandExecuteRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存命令执行信息
     *
     * @param commandExecuteDto
     */
    public void insertCommandExecute(CommandExecuteDto commandExecuteDto) {
        String sql = "INSERT INTO t_command_execute (id, commandGroupId, commandId, commandLine, startDate, status) VALUES (?, ?, ?, ?, NOW(), ?)";
        this.jdbcTemplate.update(sql,
                new Object[]{
                        UUID.randomUUID().toString(),
                        commandExecuteDto.getCommandGroupId(),
                        commandExecuteDto.getCommandId(),
                        commandExecuteDto.getCommandLine(),
                        0
                });
    }

    /**
     * 更新命令执行状态
     *
     * @param commandId
     * @param commandResult
     */
    public void updateCommandExecute(String commandId, String commandResult) {
        String sql = "UPDATE t_command_execute SET commandResult = ?, endDate = NOW(), status = 1 WHERE commandId = ?";
        this.jdbcTemplate.update(sql, new Object[]{commandResult, commandId});
    }

    /**
     * 获取命令调度执行列表
     *
     * @param commandGroupId
     * @return
     */
    public List<CommandExecuteDto> queryCommandExecuteListByGroupId(String commandGroupId) {
        String sql = "SELECT id, commandGroupId, commandId, commandLine, startDate, endDate, commandResult, status FROM t_command_execute WHERE commandGroupId = ?";
        List<CommandExecuteDto> list = this.jdbcTemplate.query(sql, new Object[]{commandGroupId}, new CommandExecuteRowMapper());
        return list;
    }

    /**
     * 获取命令执行信息
     *
     * @param commandId
     * @return
     */
    public CommandExecuteDto queryCommandExecuteListByCommandId(String commandId) {
        String sql = "SELECT id, commandGroupId, commandId, commandLine, startDate, endDate, commandResult, status FROM t_command_execute WHERE commandId = ?";
        List<CommandExecuteDto> list = this.jdbcTemplate.query(sql, new Object[]{commandId}, new CommandExecuteRowMapper());
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
}
